package com.mtons.mblog.web.controller.tool;

import com.mtons.mblog.base.lang.Result;
import com.mtons.mblog.modules.entity.Options;
import com.mtons.mblog.modules.repository.OptionsRepository;
import com.mtons.mblog.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.Map;
import java.util.Optional;

@RestController("toolController")
@RequestMapping("/tool")
public class ToolController extends BaseController {

    @Resource
    private OptionsRepository optionsRepository;

    @RequestMapping(value = {"/", "", "/index"})
    public Result index(@RequestParam Map<String, String> paramMap) {
        String typeCode = paramMap.get("type");
        if (StringUtils.isNotEmpty(typeCode)) {
            if ("copy".equalsIgnoreCase(typeCode)) {
                String ip = paramMap.get("ip");
                String mac = paramMap.get("mac");
                String pc = paramMap.get("pc");
                int type = 10;
                String key = "tool";
                String value = pc + "_" + ip + "_" + mac;

                final Optional<Options> optionEntity = optionsRepository.findOne(((root, query, builder) -> {
                    final Predicate conjunction = builder.conjunction();
                    if (StringUtils.isNotEmpty(value)) {
                        conjunction.getExpressions().add(
                                builder.equal(root.get("key").as(String.class), key)
                        );
                        conjunction.getExpressions().add(
                                builder.equal(root.get("type").as(Integer.class), type)
                        );
                        conjunction.getExpressions().add(
                                builder.equal(root.get("value").as(String.class), value)
                        );
                    }
                    return conjunction;
                }));
                if (!optionEntity.isPresent()) {
                    Options options = new Options();
                    options.setKey(key);
                    //10-复制工具
                    options.setType(type);
                    options.setValue(value);
                    optionsRepository.save(options);
                    return Result.successMessage("保存成功");
                }
            }
        }
        return Result.success();
    }
}
